# -*- coding: utf-8 -*-
import hashlib
import json
import time
from collections import OrderedDict

import requests
from django.conf import settings
from django.template import Context
from django.template.loader import get_template

from async import async_job
from common.cache import redis_cache
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.qr import make_code

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '00000000519492': { # 魔方支付 支付宝扫码 100-10000 2% loki
        'API_KEY': 'RIQUJiHJkPp2',
        'gateway': 'http://47.75.76.10:32089/payment/ScanPayApply.do',
        'query_gateway': 'http://47.75.76.10:32089/payment/OrderStatusQuery.do',
    },
}


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if parameter[k] != '' and parameter[k] != None:
            s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % key
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def verify_notify_sign(params, key):
    sign = params['signData']
    params.pop('signData')
    calculated_sign = generate_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("mfpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_str(s, start, end):
    p1 = s.index(start)
    p2 = s.index(end, p1 + len(start))
    if p2 > p1:
        return s[p1 + len(start): p2]
    else:
        return ''


# 00021-支付宝扫码
def _get_pay_type(service):
    if service == 'alipay':
        return '00021'
    elif service == 'wxpay':
        return '00025'
    elif service == 'union':
        return '00023'
    elif service == 'qq':  # [2.00 - 5000.00]
        return '00033'
    elif service == 'jd':
        return '00046'
    else:
        return '00021'


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>document.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info.get('service')
    parameter_dict = OrderedDict((
        ('versionId', '1.1'),
        ('orderAmount', str(int(pay_amount * 100))),
        ('orderDate', time.strftime("%Y%m%d%H%M%S", time.localtime())),
        ('currency', 'RMB'),
        ('transType', '0008'),
        ('asynNotifyUrl', '{}/pay/api/{}/mfpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('synNotifyUrl', '{}/pay/api/{}/mfpay/{}/'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('signType', 'MD5'),
        ('merId', app_id),
        ('prdOrdNo', str(pay.id)),
        ('payMode', _get_pay_type(service)),
        ('receivableType', 'D00'),
        ('prdAmt', str(int(pay_amount * 100))),
        ('prdDisUrl', ''),
        ('prdName', 'nice'),
        ('prdShortName', ''),
        ('prdDesc', ''),
        ('merParam', ''),
    ))
    parameter_dict['signData'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("mfpay create charge data: %s ", json.dumps(parameter_dict))

    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info("mf_pay create rdp data: %s", response.text)
    data = json.loads(response.text)
    template_data = {'base64_img': make_code(data['qrcode']), 'amount': pay_amount}
    t = get_template('qr_alipay_mf.html')
    html = t.render(Context(template_data))
    cache_id = redis_cache.save_html(pay.id, html)
    _LOGGER.info("mfpay create_url: %s, pay.id: %s", settings.PAY_CACHE_URL + cache_id, pay.id)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# SUCCESS
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("mfpay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['prdOrdNo']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('mfpay event does not contain pay ID')

    pay = order_db.get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['orderStatus'])
    trade_no = data['payId']
    total_fee = float(data['orderAmount']) / 100.0

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)

    # 01 支付成功 00 未支付 02 支付处理中
    if trade_status == '01':
        _LOGGER.info('mfpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('versionId', '1.1'),
        ('signType', 'MD5'),
        ('merId', app_id),
        ('prdOrdNo', str(pay_id)),
    ))
    parameter_dict['signData'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("mfpay query  data: %s", json.dumps(parameter_dict))
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("mfpay query rsp: %s %s", response.status_code, response.text)
    if response.status_code == 200:
        trade_status = str(json.loads(response.text)['orderStatus'])
        trade_no = json.loads(response.text)['prdordno']
        total_fee = float(json.loads(response.text)['ordamt']) / 100.0

        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        # 交易订单: 00 未支付 01 支付成功 02 行处理中 14 冻结 19 待处理
        if trade_status == '01':
            _LOGGER.info('mfpay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            res = order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                           total_fee, trade_no, extend)
            if res:
                # async notify
                async_job.notify_mch(pay_order.id)
            print("order process successfully. %s" % pay_order.id)
    else:
        _LOGGER.warn('mfpay data error, status_code: %s', response.status_code)
